package com.beta.service.pay;


import com.beta.service.ServiceException;
import com.beta.em.pay.PayRoutes;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付策略上下文
 * Created by Martin on 2016/7/01.
 */
@Component
public class StrategyContext implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    private Map<PayRoutes, PayStrategy> payMap = new HashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        initPayMap();
    }

    private void initPayMap() {
        try {
            Map<String, PayStrategy> payStrategyMap = this.applicationContext.getBeansOfType(PayStrategy.class);
            if (MapUtils.isNotEmpty(payStrategyMap)) {
                payStrategyMap.forEach((name, payStrategy) -> {
                    PayRoutes[] payRoutes = payStrategy.getPayRoutes();
                    if (ArrayUtils.isNotEmpty(payRoutes)) {
                        for (PayRoutes payRoute : payRoutes) {
                            payMap.put(payRoute, payStrategy);
                        }
                    }
                });
            }
        } catch (Exception e) {
            // ignore
            e.printStackTrace();
        }
    }

    public PayStrategy getPayStrategy(PayRoutes payRoutes) {
        if (MapUtils.isEmpty(payMap) || !payMap.containsKey(payRoutes)) {
            throw new ServiceException("E60002", payRoutes);
        } else {
            return payMap.get(payRoutes);
        }
    }

}
